﻿using System.Net.Mime;
using System.Web.Mvc;
using System.Web.Security;
using EasySite.Services;
using EasySite.Web.ViewModels;
using EasySite.Web.ViewModels.Account;

namespace EasySite.Web.Controllers
{
    public class AccountController : ControllerBase
    {
        public ActionResult Register()
        {
            return View();
        }

        public ActionResult Login()
        {
            return View(new EmptyViewModel<LoginViewModel>(new LoginViewModel()));
        }

        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();
            Session.Clear();
            return RedirectToAction("Login");
        }

        [HttpPost]
        public ActionResult Login(LoginViewModel viewModel)
        {
            var service = base.GetService<IUserService>();
            if (service.Login(viewModel.Username, viewModel.Password, Request.UserHostAddress))
            {
                FormsAuthentication.SetAuthCookie(viewModel.Username, viewModel.Remember);
                return RedirectToAction("Index", "Home");
            }
            viewModel.Error = "Username or password is incorrect.";
            return View(new EmptyViewModel<LoginViewModel>(viewModel));
        }
    }
}
